<template>

  <el-card>
    <div style="font-size: 30px;">{{ isEdit ? '编辑仓库' : '基础信息' }}</div>
    <el-form ref="ruleFormRef" style="width: 100%;" :model="ruleForm" label-width="auto">
      <el-container>
        <el-aside width="600px">
          <el-form-item label="仓库编号">
            <el-input v-model="ruleForm.warehouseCode" placeholder="自动获取系统编号" readonly class="form-input">
              <template #append>
                <el-button v-if="!isEdit" @click="generateWarehouseCode" :loading="generatingCode">自动生成</el-button>
                <el-button v-else disabled>编辑模式</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="仓库容量/m³">
            <el-input v-model="ruleForm.warehouseCapacity" />
          </el-form-item>
          <el-form-item label="仓库主管">
            <el-select v-model="ruleForm.userId" @click="dialogFormVisibles = true">
              <el-option v-for="item in datas" :label="item.userName" :value="item.userId" />
              <el-option />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库地址">
            <el-input v-model="ruleForm.warehouseAddress" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="ruleForm.warehouseSort" />
          </el-form-item>
          <el-form-item v-if="ruleForm.warehouseState != '2'" label="锁定">
            <el-switch v-model="ruleForm.warehouseLock" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input type="textarea" v-model="ruleForm.warehouseNote" />
          </el-form-item>
        </el-aside>
        <el-aside width="600px">
          <el-form-item label="仓库名称">
            <el-input v-model="ruleForm.warehouseName" />
          </el-form-item>
          <el-form-item label="库管部门" style="margin-top: 40px;">
            <el-input v-model="selectedOrganizationName" placeholder="请选择库管部门" readonly
              @click="openOrganizationDialog">
              <template #append>
                <el-button icon="Search" @click="openOrganizationDialog">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="联系电话" style="margin-top: 40px;">
            <el-input v-model="ruleForm.warehousePhone" />
          </el-form-item>
          <el-form-item label="仓库状态" style="margin-top: 30px;">
            <el-radio-group v-model="ruleForm.warehouseState">
              <el-radio value="1">启用</el-radio>
              <el-radio value="2">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-aside>
      </el-container>

    </el-form>
  </el-card>
  <el-card>
    <div style="font-size: 30px;">库区信息</div>
    <div style="margin-bottom: 15px;">
      <el-button type="success" @click="dialog = true">新增</el-button>
      <el-button type="primary" @click="importDialog = true" style="margin-left: 10px;">导入库位</el-button>
    </div>
    <el-table :data="tableDatastoragelocation" style="width: 100%">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="storagelocationCode" label="库位编号" width="140">
        <template #default="scope">
          <el-input 
            v-model="scope.row.storagelocationCode" 
            size="small" 
            :disabled="!isEdit"
            placeholder="库位编号"
          />
        </template>
      </el-table-column>
      <el-table-column prop="storagelocationName" label="库位名称" width="140">
        <template #default="scope">
          <el-input 
            v-model="scope.row.storagelocationName" 
            size="small" 
            :disabled="!isEdit"
            placeholder="库位名称"
          />
        </template>
      </el-table-column>
      <el-table-column prop="storagelocationCapacity" label="库位容量" width="140">
        <template #default="scope">
          <el-input 
            v-model="scope.row.storagelocationCapacity" 
            size="small" 
            :disabled="!isEdit"
            placeholder="库位容量"
          />
        </template>
      </el-table-column>
      <el-table-column prop="storagelocationSort" label="排序" width="120">
        <template #default="scope">
          <el-input-number 
            v-model="scope.row.storagelocationSort" 
            size="small" 
            :disabled="!isEdit"
            :min="0"
            :controls="false"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="库位主管" width="140" v-if="isEdit">
        <template #default="scope">
          <el-select 
            v-model="scope.row.userId" 
            size="small" 
            :disabled="!isEdit"
            placeholder="选择主管"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="user in datas"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="storagelocationState" label="库位状态" width="140">
        <template #default="scope">
          <el-select 
            v-model="scope.row.storagelocationState" 
            size="small" 
            :disabled="!isEdit"
            style="width: 100%"
          >
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="storagelocationNote" label="备注" width="180">
        <template #default="scope">
          <el-input 
            v-model="scope.row.storagelocationNote" 
            size="small" 
            :disabled="!isEdit"
            placeholder="备注"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" v-if="isEdit" fixed="right">
        <template #default="scope">
          <el-button 
            link
            type="primary" 
            size="small" 
            @click="saveStoragelocation(scope.row)"
            :loading="scope.row.saving"
          >
            保存
          </el-button>
          <el-button 
            link
            type="danger" 
            size="small" 
            @click="deleteStoragelocation(scope.row, scope.$index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <table>
      <tbody>
        <th>
        <td>
          <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
            :page-sizes="[10, 20, 30, 40]" prev-text="上一页" next-text="下一页" :background="true" layout="slot"
            :total="page.listCount">
            <template #default="spoce">
              共{{ page.listCount }}条,每页{{ page.pagesize }}条,当前第{{ page.pageindex }}/{{ page.pageCount }}页
            </template>
          </el-pagination>
        </td>
        <td>
          <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
            :page-sizes="[10, 20, 30, 40]" prev-text="上一页" next-text="下一页" :background="true"
            layout="slot, prev, pager, next" :total="page.listCount">
            <template #default="spoce">
              <el-button link type="primary" size="small" @click="page.pageindex = 1">首页</el-button>
            </template>
          </el-pagination>
        </td>
        <td>
          <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
            :page-sizes="[10, 20, 30, 40]" prev-text="上一页" next-text="下一页" :background="true"
            layout="slot, sizes, jumper" :total="page.listCount">
            <template #default="spoce">
              <el-button link type="primary" size="small" @click="page.pageindex = page.pageCount">
                尾页
              </el-button>
            </template>
          </el-pagination>
        </td>
        </th>
      </tbody>
    </table>
  </el-card>
  <el-dialog v-model="dialogFormVisible" title="选择库管部门" width="500" :close-on-click-modal="false">
    <div class="organization-dialog">
      <el-input v-model="organizationSearchText" class="w-60 mb-2" placeholder="请输入部门名称或编号" clearable />
      <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="organizationTree"
        :props="organizationTreeProps" :filter-node-method="filterNode" default-expand-all highlight-current
        :expand-on-click-node="false" @node-click="handleOrganizationSelect" />
    </div>
    <template #footer>
      <el-button @click="dialogFormVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogFormVisibles" width="500">
    <el-input v-model="ruleForm.userId" class="w-60 mb-2" placeholder="请搜索" />
    <span style="font-size: 25px;">人力资源部</span>
    <el-tree style="max-width: 600px" :data="datas" :props="defaultPropes" accordion @node-click="handleNodeClicks" />
    <el-button type="success" size="small" @click="dialogFormVisibles = false">保存</el-button>
  </el-dialog>
  <el-card>
    <el-button style="float: right ;margin-bottom: 15px;" type="success" @click="save">保存</el-button>
  </el-card>
  <el-drawer v-model="dialog" title="新增" :before-close="handleClose" direction="rtl" class="demo-drawer" size="720px">
    <div class="demo-drawer__content" style="overflow: visible;">
      <el-form :label-width="formLabelWidth">
        <el-container>
          <el-aside width="360px">
            <span>库位编号</span><br />
            <el-input v-model="addstoragelocation.storagelocationCode" placeholder="自动获取系统编号" readonly
              class="form-input storage-input">
              <template #append>
                <el-button @click="generateStoragelocationCode" :loading="generatingLocationCode">自动生成</el-button>
              </template>
            </el-input>
            <span>库位容量/m³</span><br />
            <el-input v-model="addstoragelocation.storagelocationCapacity" />
            <span>库位状态</span><br />
            <el-radio-group v-model="addstoragelocation.storagelocationState">
              <el-radio :value=1>启用</el-radio>
              <el-radio :value=2>停用</el-radio>
            </el-radio-group>
          </el-aside>
          <el-main style="width: 40px;"></el-main>
          <el-aside width="360px">
            <span>库位名称</span><br />
            <el-input v-model="addstoragelocation.storagelocationName" />
            <span>排序</span><br />
            <el-input v-model="addstoragelocation.storagelocationSort" />
            <span>仓库主管</span><br />
            <el-select v-model="addstoragelocation.userId" @click="dialogFormVisiblea = true">
              <el-option v-for="item in datas" :label="item.userName" :value="item.userId" />
              <el-option />
            </el-select>
          </el-aside>
        </el-container>
        <span>备注</span><br />
        <el-input v-model="form.desc" type="textarea" />
      </el-form>
      <div class="demo-drawer__footer" style="margin-bottom: auto;">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="success" :loading="loading" @click="onClick">
          保存
        </el-button>
      </div>
    </div>
  </el-drawer>
  <el-dialog v-model="dialogFormVisiblea" width="500">
    <el-input v-model="ruleForm.userId" class="w-60 mb-2" placeholder="请搜索" />
    <span style="font-size: 25px;">仓储部</span>
    <el-tree style="max-width: 600px" :data="datas" :props="defaultPropes" accordion @node-click="handleNodeClickes" />
    <el-button type="success" size="small" @click="dialogFormVisiblea = false">保存</el-button>

  </el-dialog>

  <!-- 库位导入对话框 -->
  <el-dialog v-model="importDialog" title="库位导入" width="600px">
    <div style="margin-bottom: 20px;">
      <el-alert title="导入说明" type="info" :closable="false" show-icon>
        <template #default>
          <p>1. 请使用Excel文件格式(.xlsx或.xls)</p>
          <p>2. Excel文件列顺序：<strong>仓库编号、库位名称、库位编号、库位容量、用户编号、排序、状态、备注</strong></p>
          <p>3. <strong>库位名称</strong>和<strong>库位编号</strong>为必填项，库位编号必须唯一</p>
          <p>4. 状态：1-启用，2-停用（默认为1）</p>
          <p>5. 用户编号：库位主管的用户ID（可为空，默认为0）</p>
          <p>6. 第一行为标题行，数据从第二行开始</p>
          <div style="margin-top: 10px;">
            <el-button size="small" type="primary" @click="downloadTemplate">下载导入模板</el-button>
          </div>
        </template>
      </el-alert>
    </div>

    <el-form :model="importForm" label-width="120px">
      <el-form-item label="选择文件">
        <el-upload ref="uploadRef" :auto-upload="false" :limit="1" :on-change="handleFileChange"
          :on-remove="handleFileRemove" accept=".xlsx,.xls" drag>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 xlsx/xls 文件
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="覆盖模式">
        <el-switch v-model="importForm.overwrite" active-text="覆盖已存在的库位" inactive-text="跳过已存在的库位" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="importDialog = false">取消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importLoading">
          开始导入
        </el-button>
      </div>
    </template>

  </el-dialog>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch, computed } from 'vue'
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
import { ElMessageBox, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import myaxios from "@/http/MyAxios";

// 判断是新增还是编辑
const isEdit = computed(() => !!route.query.warehouseId)
const warehouseIdFromRoute = computed(() => route.query.warehouseId ? String(route.query.warehouseId) : null)

onMounted(() => {
  if (isEdit.value && warehouseIdFromRoute.value) {
    // 编辑模式：加载仓库信息和明细
    loadWarehouseDetail(Number(warehouseIdFromRoute.value))
  } else {
    // 新增模式：初始化本地明细列表
    tableDatastoragelocation.value = []
    warehouseId.value = null
  }
  getorganizationservices();
  getuser();
})
const ruleFormRef = ref<FormInstance>()
const generatingCode = ref(false)
const generatingLocationCode = ref(false)
//分页条件
const page = reactive({
  pageindex: 1,
  pagesize: 10,
  listCount: 0,
  pageCount: 0
})
const ruleForm = reactive({
  "warehouseCode": "",
  "warehouseName": "",
  "warehouseCapacity": "",
  "userId": "",
  "storagelocationNum": page.listCount,
  "warehouseAddress": "",
  "warehouseSort": "",
  "warehouseLock": false,
  "warehouseNote": "",
  "organizationId": "",
  "warehousePhone": "",
  "accountName": "",
  "warehouseState": "1" as string | null
})

const warehouseId = ref<number | null>(null)
const tableDatastoragelocation = ref<any[]>([])

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })

  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode, targetName }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode, targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateWarehouseCode = async () => {
  generatingCode.value = true
  try {
    ruleForm.warehouseCode = await requestNumber('Warehouse', '仓库')
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

const generateStoragelocationCode = async () => {
  generatingLocationCode.value = true
  try {
    addstoragelocation.storagelocationCode = await requestNumber('StorageLocation', '库位')
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingLocationCode.value = false
  }
}

// 加载仓库详情和明细
const loadWarehouseDetail = async (id: number) => {
  try {
    // 加载仓库基本信息
    const res = await myaxios.get(`/api/Warehouse/DetailWarehouse?warehouseid=${id}`)
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      // 反填仓库基本信息
      ruleForm.warehouseCode = data.warehouseCode || ''
      ruleForm.warehouseName = data.warehouseName || ''
      ruleForm.warehouseCapacity = data.warehouseCapacity || ''
      ruleForm.userId = String(data.userId || '')
      ruleForm.warehouseAddress = data.warehouseAddress || ''
      ruleForm.warehouseSort = String(data.warehouseSort || '')
      ruleForm.warehouseLock = data.warehouseLock || false
      ruleForm.warehouseNote = data.warehouseNote || ''
      ruleForm.organizationId = String(data.organizationId || '')
      ruleForm.warehousePhone = data.warehousePhone || ''
      ruleForm.warehouseState = data.warehouseState ? String(data.warehouseState) : '1'
      ruleForm.accountName = data.accountName || ''
      
      // 设置选中的组织名称
      selectedOrganizationName.value = data.organizationName || ''
      
      // 设置仓库ID（用于库位管理）
      warehouseId.value = id
      
      // 加载仓库明细（库位列表）
      loadStoragelocationList(id)
    } else {
      ElMessage.error('加载仓库信息失败')
    }
  } catch (error) {
    console.error('加载仓库详情失败:', error)
    ElMessage.error('加载仓库详情失败')
  }
}

// 加载库位列表
const loadStoragelocationList = async (id: number) => {
  try {
    const res = await myaxios.get("/api/Warehouse/GetStoragelocation", {
      params: {
        warehouseId: id,
        pageindex: 1,
        pagesize: 9999 // 加载所有库位
      }
    })
    if (res.data?.code === 200 && res.data?.data) {
      const storagelocations = res.data.data.data || []
      const currentWarehouseId = Number(id)
      // 为每个库位添加 saving 属性，用于保存按钮的加载状态
      tableDatastoragelocation.value = storagelocations
        .filter((item: any) => Number(item.warehouseId) === currentWarehouseId)
        .map((item: any) => ({
          ...item,
          saving: false
        }))
      page.listCount = tableDatastoragelocation.value.length
      page.pageCount = 1
      page.pageindex = 1
    }
  } catch (error) {
    console.error('加载库位列表失败:', error)
  }
}

//添加仓库
const save = async () => {
  try {
    if (!isEdit.value) {
      // 新增模式
  if (!ruleForm.warehouseCode) {
    await generateWarehouseCode()
    if (!ruleForm.warehouseCode) {
      ElMessage.warning('请先生成仓库编号')
      return
    }
  }

      const createRes = await myaxios.post("/api/Warehouse/CreateWarehouse", ruleForm)
      if (createRes.data?.code !== 200) {
        ElMessage.error(createRes.data?.message || '新增仓库失败')
        return
      }

      const newWarehouseId = await fetchWarehouseIdByCode(ruleForm.warehouseCode)
      if (!newWarehouseId) {
        ElMessage.warning('仓库已创建，但未获取到仓库编号，库位明细未保存')
        router.push("/GetWarehouse")
        return
      }

      if (tableDatastoragelocation.value.length > 0) {
        await savePendingStoragelocations(newWarehouseId)
      }

      ElMessage.success('新增仓库成功')
      router.push("/GetWarehouse")
    } else {
      // 编辑模式
      if (!warehouseIdFromRoute.value) {
        ElMessage.error('仓库ID不存在')
        return
      }
      const updateRes = await myaxios.put(`/api/Warehouse/UpdateWarehouse?warehouseId=${warehouseIdFromRoute.value}`, ruleForm)
      if (updateRes.data?.code === 200) {
        ElMessage.success(updateRes.data?.message || '更新仓库成功')
        router.push("/GetWarehouse")
      } else {
        ElMessage.error(updateRes.data?.message || '更新仓库失败')
      }
    }
  } catch (error) {
    console.error('保存仓库失败:', error)
    ElMessage.error('保存仓库失败，请稍后重试')
}
}

const fetchWarehouseIdByCode = async (code: string) => {
  try {
    const res = await myaxios.get("/api/Warehouse/GetWarehouse", {
      params: {
        warehousecode: code,
        pageindex: 1,
        pagesize: 1
      }
    })
    const payload = res.data?.data || {}
    const list = payload.data || payload.Data || []
    const warehouse = list.find((item: any) =>
      (item.warehouseCode ?? item.WarehouseCode) === code
    )
    return warehouse?.warehouseId || warehouse?.WarehouseId || null
  } catch (error) {
    console.error('根据编号获取仓库ID失败:', error)
    return null
  }
}

const savePendingStoragelocations = async (warehouseIdToUse: number) => {
  for (const item of tableDatastoragelocation.value) {
    const payload = {
      storagelocationName: item.storagelocationName || '',
      storagelocationCode: item.storagelocationCode || '',
      storagelocationCapacity: item.storagelocationCapacity || '',
      userId: Number(item.userId) || 0,
      storagelocationSort: Number(item.storagelocationSort) || 0,
      storagelocationState: Number(item.storagelocationState) || 1,
      storagelocationNote: item.storagelocationNote || '',
      warehouseId: warehouseIdToUse
    }
    try {
      const res = await myaxios.post("/api/Warehouse/CreateStoragelocation", payload)
      if (res.data?.code !== 200) {
        ElMessage.error(res.data?.message || `库位 ${payload.storagelocationName || payload.storagelocationCode} 保存失败`)
      }
    } catch (error) {
      console.error('保存库位失败:', error)
      ElMessage.error(`库位 ${payload.storagelocationName || payload.storagelocationCode} 保存失败`)
    }
  }
}
// 部门
const selectedOrganizationName = ref('')
const organizationTree = ref<any[]>([])
const organizationTreeProps = {
  children: 'children',
  label: 'organizationName'
}

const transformOrganizationTree = (nodes: any[] = []): any[] => {
  return nodes.map(node => ({
    organizationId: node.organizationId ?? node.id,
    organizationName: node.organizationName ?? node.label ?? node.name ?? '',
    organizationCode: node.organizationCode ?? node.code,
    children: node.children ? transformOrganizationTree(node.children) : []
  }))
}

const getorganizationservices = () => {
  myaxios.get("api/Organization/GetOrganizationTree?parentid=0")
    .then(res => {
      const treeData = Array.isArray(res.data) ? res.data : []
      organizationTree.value = transformOrganizationTree(treeData)
    })
}

const openOrganizationDialog = () => {
  dialogFormVisible.value = true
}

const handleOrganizationSelect = (data: Tree) => {
  const id = data.organizationId ?? data.id
  const name = data.organizationName ?? data.label ?? ''
  ruleForm.organizationId = id ? String(id) : ''
  selectedOrganizationName.value = name
  dialogFormVisible.value = false
  ElMessage.success(`已选择 ${name}`)
}

//树形
interface Tree {
  [key: string]: any
}

const organizationSearchText = ref('')
const treeRef = ref<TreeInstance>()

watch(organizationSearchText, (val) => {
  treeRef.value?.filter(val)
})

const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  const name = data.organizationName ?? data.label ?? ''
  return name.includes(value)
}

const dialogFormVisiblea = ref(false)
const dialogFormVisible = ref(false)
//用户
const dialogFormVisibles = ref(false)
const defaultPropes = {
  label: 'userName',
  value: 'userId'
}
const handleNodeClicks = (data: Tree) => {
  console.log(data)
  ruleForm.userId = data.userId
  getuser();
}
const datas = ref([{
  userId: '',
  userName: ''
}]);
const getuser = () => {
  myaxios.get('/api/Warehouse/GetUser')
    .then(res => {
      datas.value = res.data.data
    }
    )
}
//查询条件（保留以便后续扩展）
const formInline = reactive({
  storagelocationstate: '',
  userid: '',
  name: '',
})

const getstoragelocation = () => {
  myaxios.get("/api/Warehouse/GetStoragelocation", {
    params: {
      name: formInline.name,
      warehouseId: warehouseId.value,
      userid: formInline.userid,
      storagelocationstate: formInline.storagelocationstate,
      pageindex: page.pageindex,
      pagesize: page.pagesize,
    }
  }).then(res => {
    tableDatastoragelocation.value = res.data.data.data || []
    page.listCount = tableDatastoragelocation.value.length
    page.pageCount = 1
    page.pageindex = 1
  })
}
//添加库位
const addstoragelocation = reactive({
  "storagelocationName": "",
  "storagelocationCode": "",
  "storagelocationCapacity": "",
  "userId": "",
  "storagelocationSort": "",
  "storagelocationState": "",
  "storagelocationNote": "",
  "warehouseId": null as number | null
})



const formLabelWidth = '80px'
let timer: any;
const dialog = ref(false)
const loading = ref(false)

const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})
const handleNodeClickes = (data: Tree) => {
  console.log(data)
  addstoragelocation.userId = data.userId
  getuser();
}

const addLocalStoragelocationRow = () => {
  tableDatastoragelocation.value.push({
    storagelocationName: addstoragelocation.storagelocationName,
    storagelocationCode: addstoragelocation.storagelocationCode,
    storagelocationCapacity: addstoragelocation.storagelocationCapacity,
    userId: addstoragelocation.userId,
    storagelocationSort: addstoragelocation.storagelocationSort,
    storagelocationState: addstoragelocation.storagelocationState,
    storagelocationNote: addstoragelocation.storagelocationNote,
    saving: false
  })
  page.listCount = tableDatastoragelocation.value.length
  page.pageCount = 1
  page.pageindex = 1
}

const resetAddStoragelocationForm = () => {
  addstoragelocation.storagelocationName = ''
  addstoragelocation.storagelocationCode = ''
  addstoragelocation.storagelocationCapacity = ''
  addstoragelocation.userId = ''
  addstoragelocation.storagelocationSort = ''
  addstoragelocation.storagelocationState = ''
  addstoragelocation.storagelocationNote = ''
}

const onClick = async () => {
  if (!addstoragelocation.storagelocationCode) {
    await generateStoragelocationCode()
    if (!addstoragelocation.storagelocationCode) {
      ElMessage.warning('请先生成库位编号')
      return
    }
  }
  // 新增模式：只在当前页面记录，不调用后端
  if (!isEdit.value) {
    addLocalStoragelocationRow()
    resetAddStoragelocationForm()
    loading.value = false
    dialog.value = false
    ElMessage.success('已添加到本仓库明细列表，保存仓库后会一并提交')
    return
  }

  // 编辑模式：需要后端存在仓库ID
  if (!warehouseId.value) {
    ElMessage.error('仓库ID不存在，无法添加库位')
    return
  }
  addstoragelocation.warehouseId = warehouseId.value
  myaxios.post("/api/Warehouse/CreateStoragelocation", addstoragelocation)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        // 重新加载库位列表
        if (warehouseId.value) {
          loadStoragelocationList(warehouseId.value)
      }
        resetAddStoragelocationForm()
      } else {
        ElMessage.error(res.data.message);
      }
    })
  loading.value = false
  dialog.value = false
}

// 保存库位（编辑模式）
const saveStoragelocation = async (row: any) => {
  if (!row.storagelocationId) {
    ElMessage.warning('库位ID不存在')
    return
  }
  
  row.saving = true
  try {
    const res = await myaxios.put(`/api/Warehouse/UpdateStoragelocation?storagelocationId=${row.storagelocationId}`, {
      storagelocationId: row.storagelocationId,
      storagelocationCode: row.storagelocationCode || '',
      storagelocationName: row.storagelocationName || '',
      storagelocationCapacity: row.storagelocationCapacity || '',
      userId: Number(row.userId) || 0,
      storagelocationSort: Number(row.storagelocationSort) || 0,
      storagelocationState: Number(row.storagelocationState) || 1,
      storagelocationNote: row.storagelocationNote || '',
      warehouseId: Number(row.warehouseId) || warehouseId.value || 0
    })
    
    if (res.data?.code === 200) {
      ElMessage.success('保存库位成功')
      // 重新加载库位列表以获取最新数据
      if (warehouseId.value) {
        loadStoragelocationList(warehouseId.value)
      }
    } else {
      ElMessage.error(res.data?.message || '保存库位失败')
    }
  } catch (error) {
    console.error('保存库位失败:', error)
    ElMessage.error('保存库位失败')
  } finally {
    row.saving = false
  }
}

// 删除库位（编辑模式）
const deleteStoragelocation = (row: any, index: number) => {
  if (!row.storagelocationId) {
    ElMessage.warning('库位ID不存在')
    return
  }
  
  ElMessageBox.confirm(
    `确认删除库位 "${row.storagelocationName || row.storagelocationCode}" 吗?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 使用批量删除接口删除单个库位
      myaxios.put(`/api/Warehouse/AllDeleteStoragelocation?storagelocationIds=${row.storagelocationId}`)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message || '删除库位成功')
            // 重新加载库位列表
            if (warehouseId.value) {
              loadStoragelocationList(warehouseId.value)
            }
          } else {
            ElMessage.error(res.data.message || '删除库位失败')
          }
        })
        .catch(error => {
          console.error('删除库位失败:', error)
          ElMessage.error('删除库位失败')
        })
    })
    .catch(() => {
      // 用户取消
    })
}

const handleClose = (done: any) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('是否提交添加库位?')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 2000)
    })
    .catch(() => {
      // catch error
    })
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
  clearTimeout(timer)
}

// 导入相关变量和方法
const importDialog = ref(false)
const importLoading = ref(false)
const uploadRef = ref()
const selectedFile = ref(null)

const importForm = reactive({
  overwrite: false
})

// 文件选择处理
const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

// 文件移除处理
const handleFileRemove = () => {
  selectedFile.value = null
}

// 执行导入
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  if (!warehouseId.value) {
    ElMessage.warning('请先创建仓库或选择目标仓库')
    return
  }

  // 确认导入操作
  try {
    await ElMessageBox.confirm(
      `确定要导入文件 吗？${importForm.overwrite ? '将覆盖已存在的库位。' : '将跳过已存在的库位。'}`,
      '确认导入',
      {
        confirmButtonText: '确定导入',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return // 用户取消
  }

  importLoading.value = true

  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('warehouseId', String(warehouseId.value || ''))
    formData.append('overwrite', importForm.overwrite.toString())

    console.log('发送导入请求:', {
      fileName: selectedFile.value,
      warehouseId: warehouseId.value,
      overwrite: importForm.overwrite
    });

    const response = await myaxios.post('/api/Warehouse/ImportStoragelocation', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    console.log('导入响应:', response.data);

    // 根据后端ApiResult结构判断成功状态
    if (response.data && (response.data.success === true || response.data.code === 200)) {
      ElMessage.success('导入完成！')

      // 显示详细结果
      const resultMessage = response.data.data || response.data.message || '导入完成'

      // 使用更友好的结果展示
      ElMessageBox({
        title: '导入结果',
        message: `<div style="white-space: pre-line; text-align: left;">${resultMessage}</div>`,
        type: 'success',
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        showClose: false
      }).then(() => {
        // 刷新库位列表
        getstoragelocation()

        // 关闭对话框并重置
        importDialog.value = false
        selectedFile.value = null
        uploadRef.value?.clearFiles()
        importForm.overwrite = false
      })

    } else {
      // 处理失败情况
      const errorMessage = response.data?.message || response.data?.data || '导入失败'
      ElMessage.error('导入失败')

      // 显示错误详情
      ElMessageBox({
        title: '导入失败详情',
        message: `<div style="white-space: pre-line; text-align: left; color: #f56c6c;">${errorMessage}</div>`,
        type: 'error',
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        showClose: false
      })
    }
  } catch (error: any) {
    console.error('导入异常:', error)

    let errorMessage = '导入失败'
    if (error.response?.data) {
      errorMessage = error.response.data.message || error.response.data.data || errorMessage
    } else if (error.message) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)

    // 显示详细错误信息
    ElMessageBox.alert(errorMessage, '导入异常', {
      confirmButtonText: '确定',
      type: 'error'
    })
  } finally {
    importLoading.value = false
  }
}

// 下载导入模板
const downloadTemplate = () => {
  // 创建模板数据
  const templateData = [
    ['仓库编号', '库位名称', '库位编号', '库位容量', '用户编号', '排序', '状态', '备注'],
    ['示例：WH001', '示例：A区01号', 'A-01', '100', '1', '1', '1', '示例备注'],
    ['', '必填项', '必填项', '可选', '可选(默认0)', '可选(默认0)', '可选(默认1)', '可选']
  ]

  // 创建CSV内容
  const csvContent = templateData.map(row => row.join(',')).join('\n')

  // 创建Blob对象
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })

  // 创建下载链接
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '库位导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  ElMessage.success('模板下载成功！')
}
</script>

<style scoped>
:deep(.form-input) {
  width: 360px !important;
}

:deep(.form-input .el-input__wrapper) {
  width: 100% !important;
}
</style>